package cn.shengchao.examstar.pay.model.service.fy.response;

import cn.shengchao.examstar.pay.model.service.fy.dto.ParameterCollection;
import cn.shengchao.examstar.pay.model.service.fy.dto.PaymentDetails;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.List;

public class FuYouApiResponse {

    private ParameterCollection parameters;
    private String rawXml;
    private boolean parseError = false;
    private PaymentDetails paymentDetails;

    public FuYouApiResponse(String xmlStr) {
        this.rawXml = xmlStr;
        try {
            this.parameters = parseXmlToParameterCollection(xmlStr);
            paymentDetails = new PaymentDetails();
            paymentDetails.setAppId(parameters.getValue("sdk_appid"));
            paymentDetails.setTimeStamp(parameters.getValue("sdk_timestamp"));
            paymentDetails.setNonceStr(parameters.getValue("sdk_noncestr"));
            paymentDetails.setPackageStr(parameters.getValue("sdk_package"));
            paymentDetails.setSignType(parameters.getValue("sdk_signtype"));
            paymentDetails.setPaySign(parameters.getValue("sdk_paysign"));
        } catch (DocumentException e) {
            this.parseError = true;
            this.parameters = new ParameterCollection(); // Initialize to empty on error
            System.err.println("Failed to parse API response XML: " + e.getMessage());
            // Optionally, add a parameter indicating the error
            this.parameters.add("internal_parse_error", e.getMessage());
        }
    }

    private ParameterCollection parseXmlToParameterCollection(String xmlStr) throws DocumentException {
        ParameterCollection collection = new ParameterCollection();
        if (xmlStr == null || xmlStr.trim().isEmpty()) {
            return collection;
        }
        Document doc = DocumentHelper.parseText(xmlStr);
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked") // dom4j uses raw types
        List<Element> children = root.elements();
        if (children != null) {
            for (Element child : children) {
                collection.add(child.getName(), child.getStringValue().trim());
            }
        }
        return collection;
    }

    public PaymentDetails getPaymentDetails() {
        return paymentDetails;
    }

    public void setPaymentDetails(PaymentDetails paymentDetails) {
        this.paymentDetails = paymentDetails;
    }

    public String getParameter(String name) {
        return parameters.getValue(name);
    }

    public ParameterCollection getAllParameters() {
        return parameters; // Consider returning a defensive copy if mutable
    }

    public String getSign() {
        return parameters.getValue("sign");
    }

    public String getRawXml() {
        return rawXml;
    }

    public boolean hasParseError() {
        return parseError;
    }

    // Common FuYou response fields (adjust names as per actual API)
    public String getRespCode() {
        return getParameter("result_code"); // e.g., "000000" for success
    }

    public String getRespDesc() {
        return getParameter("resp_desc");
    }

    // Aliases for more generic terms if used
    public String getResultCode() {
        return getParameter("result_code");
    }

    public String getResultMessage() {
        return getParameter("result_msg");
    }


    public boolean isSuccess() {
        if (parseError) return false;
        // Fallback to other common success indicators if resp_code is not present
        String resultCode = getResultCode();
        if (resultCode == null) {
            return false;
        }
        if (!"000000".equalsIgnoreCase(resultCode)) {
            return false;
        }
        if (getParameter("trans_stat") == null) {
            return false;
        }
        return "SUCCESS".equals(getParameter("trans_stat"));
    }
}
